import { ArgumentMetadata, BadRequestException, PipeTransform } from "@nestjs/common";
import { ZodSchema } from "zod";

/**
 * 基于对象架构验证
 */
export class ZodValidationPipe implements PipeTransform {
  constructor(private schema: ZodSchema) {}
  /**
   * 验证 value 是否匹配
   * @param value 是传递进来的值
   * @param metadata 元数据
   * @returns 验证通过返回值
   */
  transform(value: any, metadata: ArgumentMetadata) {
    try {
      return this.schema.parse(value)
    } catch(error) {
      console.log(error.message)
      throw new BadRequestException('Validation failed')
    }
  }
}
